using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;

namespace Smarly.Bussines.Membership
{
	public static class AuthecationExtention
	{
		public static string AuthDomain(this HttpRequestBase request)
		{
			try
			{
#if DEBUG
				if (request.Url.Host == "178.124.171.146")
				{
					return request.Url.Host;
				}
				else
#endif
				{
					var hostSegments = request.Url.Host.Split('.');

					string domain = string.Empty;
					for (int i = hostSegments.Length - 1; i > hostSegments.Length - 3; i--)
					{
						domain = "." + hostSegments[i] + domain;
					}

					return domain;
				}
			}
			catch
			{
				return null;
			}
		}

		public static void LogOut(this HttpResponseBase response, HttpRequestBase request, string cookieName = ".auth")
		{
			response.Cookies.Add(new HttpCookie(cookieName, string.Empty) { Path = "/", Domain = request.AuthDomain(), Expires = new DateTime(1900, 1, 1) }); 
		}

		public static void LogIn(this HttpResponseBase response, HttpRequestBase request, string email, string userHash, DateTime? expireDate = null, bool remember = true, string cookieName = ".auth")
		{
			DateTime expire = expireDate.HasValue ? expireDate.Value : DateTime.Now.AddYears(1);
			string value = Serializer.Diserialize(new Pair {First = email, Second = userHash});
			string hash = SmarlyCryptography.EncryptData(value);

			

			HttpCookie authCookie = new HttpCookie(cookieName, hash) { Path = "/", Domain = request.AuthDomain() };

			if (expire < DateTime.Now || remember)
				authCookie.Expires = expire;

			response.Cookies.Add(authCookie);
		}


	}
}